<template>
	<view class="activity-page">
		<!-- 顶部搜索框 -->
		<view class="header">
			<view class="search-box">
				<image src="/static/search.png" class="search-icon"></image>
				<input type="text" placeholder="请输入搜索活动" placeholder-class="placeholder-style" v-model="state.title" />
			</view>
			<view class="add-btn" v-if="state.usertype" @click="toCreateActivity()">添加活动</view>

		</view>

		<!-- 筛选条件 -->
		<view class="filter-bar">
			<view class="filter-item" @tap="togglePopup('type')">
				<text>{{
          state.activityTypes.find((type) => type.value === state.selectedType)
            ?.label || "活动类型"
        }}</text>
				<view class="arrow-icon"></view>
			</view>
			<view class="filter-item" @tap="toggleTimeSort">
				<text>时间</text>
				<view class="sort-icon">
					<text v-if="state.timeSort === 'asc'">↑</text>
					<text v-else-if="state.timeSort === 'desc'">↓</text>
					<text v-else>↕</text>
				</view>
			</view>
		</view>

		<!-- 活动列表 -->
		<view class="activity-list">
			<view class="activity-card" v-for="(activity, index) in state.filteredList" :key="index">
				<view class="activity-content">
					<image :src="activity.event_pic_url" mode="aspectFill" class="activity-img" @error="
		      () => (activity.event_pic_url = '../../static/no-image.png')
		    " />
					<view class="activity-info">
						<view class="activity-title">{{ activity.title }}</view>
						<view class="activity-meta">
							<view class="meta-item">
								<img src="/static/location.png" class="iconfont icon-location" />

								<view>{{ activity.event_location }}</view>
							</view>
							<view class="meta-item">
								<img src="/static/time.png" class="iconfont" />

								<view>
									{{formatDateTime(activity.start_time)}}-{{formatDateTime(activity.end_time)}}
								</view>
							</view>
							<view class="meta-item">
								<img src="/static/person.png" class="iconfont" />

								<view>{{ activity.now_count }}/{{ activity.max_count }}</view>
							</view>
						</view>
					</view>
					<view class="points">{{ activity.jackpoint }}积分</view>

					<view v-if="state.usertype">
						<view class="finish-btn" v-if=" state.selectedType == 2 " @click="finishActivity(activity)">
							完成活动</view>
						<view class="sign-up-btn" @click="toActivityDetail(activity._id)"> 修改活动</view>
					</view>
					<view v-else>
						<view class="sign-up-btn" v-if="activity.status == 1" @click="toActivityDetail(activity._id)"> 立即报名</view>
					</view>
				</view>
			</view>
		</view>


		<!-- 活动类型选择弹窗 -->
		<uni-popup ref="typePopup" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text>选择活动类型</text>
					<text class="close" @tap="togglePopup('type', false)">关闭</text>
				</view>
				<view class="popup-list">
					<view class="popup-item" v-for="type in state.activityTypes" :key="type.value"
						@tap="selectType(type)" :class="{ active: state.selectedType === type.label }">
						{{ type.label }}
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 活动时间选择弹窗 -->
		<uni-popup ref="timePopup" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text>选择活动时间</text>
					<text class="close" @tap="togglePopup('time', false)">关闭</text>
				</view>
				<view class="popup-list">
					<view class="popup-item" v-for="time in state.activityTimes" :key="time.value"
						@tap="selectTime(time)" :class="{ active: state.selectedTime === time.label }">
						{{ time.label }}
					</view>
				</view>
			</view>
		</uni-popup>


		<custom-tabbar currentPath="/pages/activity/activity"></custom-tabbar>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		onMounted,
		watch
	} from "vue";
	import {
		request,
		formatDateTime
	} from "../../js/util.js";
	import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
	import {
		onShow
	} from '@dcloudio/uni-app';
	const typePopup = ref(null);
	const timePopup = ref(null);

	const state = reactive({
		usertype: false,
		title: "",
		selectedType: null,
		timeSort: '', // 修改时间筛选为排序方式：'' - 默认, 'asc' - 升序, 'desc' - 降序
		activityList: [], // 原始数据
		filteredList: [], // 添加筛选后的数据列表
		activityTypes: [{
				label: "全部",
				value: null
			},
			{
				label: "未开始",
				value: 0
			},
			{
				label: "报名中",
				value: 1
			},
			{
				label: "进行中",
				value: 2
			},
			{
				label: "已结束",
				value: 3
			},
		],
		activityTimes: [{
				label: "全部时间",
				value: "all"
			},
			{
				label: "今天",
				value: "today"
			},
			{
				label: "明天",
				value: "tomorrow"
			},
			{
				label: "本周",
				value: "thisWeek"
			},
			{
				label: "本月",
				value: "thisMonth"
			},
		],
	});

	// 添加防抖函数
	const debounce = (fn, delay = 300) => {
		let timer = null;
		return function(...args) {
			if (timer) clearTimeout(timer);
			timer = setTimeout(() => {
				fn.apply(this, args);
			}, delay);
		};
	};

	// 获取活动列表
	const getActivityList = async () => {
		let submitData
		if (state.selectedType == null) {
			submitData = {
				condition: {},
			};
		} else {
			submitData = {
				condition: {
					status: state.selectedType,
				},
			};
		}

		let data = await request("selectActivity", submitData);
		console.log("getActivityList", data);
		state.activityList = data.result;
		filterActivityList(); // 获取数据后立即进行筛选
	};

	// 获取活动列表
	const finishActivity = async (data) => {

		let updateData = data
		updateData.status = 3
		const result = await request('updateActivity', {
			updateId: data._id,
			updateData,
			status: 2
		})
		if (result.status) {
			uni.showToast({
				title: '更新成功',
				icon: 'success'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		} else {
			uni.showToast({
				title: result.message || '更新失败',
				icon: 'none'
			})
		}
	};

	// 筛选并排序活动列表
	const filterActivityList = () => {
		// 先进行搜索筛选
		let filtered = state.activityList;
		if (state.title) {
			filtered = filtered.filter(activity =>
				activity.title.toLowerCase().includes(state.title.toLowerCase())
			);
		}

		// 根据end_time时间戳排序
		if (state.timeSort) {
			filtered.sort((a, b) => {
				// 直接使用时间戳比较，不需要转换
				return state.timeSort === 'asc' ?
					a.end_time - b.end_time :
					b.end_time - a.end_time;
			});
		}

		state.filteredList = filtered;
	};

	// 创建防抖搜索方法
	const debouncedSearch = debounce(filterActivityList, 300);

	// 监听搜索输入和排序方式变化
	watch([() => state.title, () => state.timeSort], () => {
		debouncedSearch();
	});

	// 统一处理弹窗显示和隐藏
	const togglePopup = (type, isShow = true) => {
		const popup = type === "type" ? typePopup : timePopup;
		if (isShow) {
			popup.value.open();
		} else {
			popup.value.close();
		}
	};

	// 选择活动类型
	const selectType = (type) => {
		state.selectedType = type.value;
		togglePopup("type", false);
		// 这里可以触发筛选
		getActivityList()
	};

	// 选择活动时间
	const selectTime = (time) => {
		state.selectedTime = time.label;
		togglePopup("time", false);
		// 这里可以触发筛选
	};

	// 切换时间排序方式
	const toggleTimeSort = () => {
		if (!state.timeSort) {
			state.timeSort = 'asc';
		} else if (state.timeSort === 'asc') {
			state.timeSort = 'desc';
		} else {
			state.timeSort = '';
		}
		filterActivityList();
	};

	const toActivityDetail = (id) => {
		console.log("id :>> ", id);
		const userInfo = uni.getStorageSync('userInfo');
		console.log('userInfo', userInfo)
		if (userInfo.role == 'admin') {
			uni.navigateTo({
				url: `/pages/createActivity/createActivity?id=${id}`,
			});
		} else {
			uni.navigateTo({
				url: `/pages/activityDetail/activityDetail?id=${id}`,
			});
		}

	};

	const toCreateActivity = () => {
		uni.navigateTo({
			url: "/pages/createActivity/createActivity"
		})
	}

	// 页面加载时获取数据
	onShow(() => {
		getActivityList();
		const userInfo = uni.getStorageSync('userInfo');
		console.log('userInfo', userInfo)
		if (userInfo.role == 'admin') {
			state.usertype = true
		} else {
			state.usertype = false
		}
	});
</script>

<style lang="scss">
	.activity-page {
		background-color: #f8f8f8;
		min-height: 100vh;

		.header {
			background-color: #fff;
			padding: 20rpx;
			width: 100%;
			display: flex;
			align-items: center;

			.add-btn {
				background: linear-gradient(to top right, #ff8980, #f22d29);
				color: #fff;
				font-size: 28rpx;
				padding: 8rpx 32rpx;
				border-radius: 24rpx;
				line-height: 1.5;
				border: none;
				box-shadow: 0 4rpx 8rpx rgba(255, 107, 107, 0.2);
				margin: 0 30rpx;
			}
		}

		// 搜索框
		.search-box {
			background-color: #f5f5f5;
			height: 80rpx;
			border-radius: 40rpx;
			display: flex;
			align-items: center;
			padding: 0 30rpx;
			flex: 1;



			.search-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 20rpx;
			}

			input {
				flex: 1;
				font-size: 28rpx;
			}

			.placeholder-style {
				color: #999;
			}
		}



		// 筛选条件
		.filter-bar {
			display: flex;
			justify-content: space-between;
			padding: 20rpx 30rpx;
			background-color: #fff;

			.filter-item {
				display: flex;
				align-items: center;
				font-size: 28rpx;
				color: #333;

				.arrow-icon {
					width: 0;
					height: 0;
					border-left: 8rpx solid transparent;
					border-right: 8rpx solid transparent;
					border-top: 12rpx solid #999; // 灰色倒三角
					margin-left: 8rpx;
				}
			}
		}

		// 活动列表
		.activity-list {
			padding: 20rpx 20rpx 200rpx 20rpx;

			.activity-card {
				background: #fff;
				border-radius: 16rpx;
				margin-bottom: 20rpx;
				padding: 20rpx;

				.activity-content {
					display: flex;
					position: relative;
					padding-bottom: 20rpx;

					.points {
						position: absolute;
						top: -20rpx;
						left: -20rpx;
						font-size: 24rpx;
						color: #fff;
						background-color: #ff6b6b;
						padding: 4rpx 16rpx;
						border-radius: 16rpx 0 16rpx 0;
					}

					.activity-img {
						width: 200rpx;
						height: 150rpx;
						border-radius: 8rpx;
					}

					.activity-info {
						flex: 1;
						margin-left: 20rpx;
						padding-right: 120rpx;

						.activity-title {
							font-size: 28rpx;
							font-weight: 500;
							color: #333;
							line-height: 1.4;
						}

						.activity-meta {
							margin-top: 16rpx;
							font-size: 24rpx;
							color: #666;

							.meta-item {
								display: flex;
								align-items: center;
								margin-bottom: 8rpx;

								.iconfont {
									margin-right: 8rpx;
									font-size: 24rpx;
									width: 30rpx;
									height: 30rpx;
								}
							}
						}
					}

					.sign-up-btn {
						position: absolute;
						right: 0;
						bottom: 0;
						background: linear-gradient(to top right, #ff8980, #f22d29);
						color: #fff;
						font-size: 24rpx;
						padding: 8rpx 32rpx;
						border-radius: 24rpx;
						line-height: 1.5;
						border: none;
						box-shadow: 0 4rpx 8rpx rgba(255, 107, 107, 0.2);

						&::after {
							border: none;
						}

						&:active {
							transform: scale(0.98);
						}
					}

					.finish-btn {
						position: absolute;
						right: 0;
						bottom: 70rpx;
						background: linear-gradient(to top right, #ff8980, #f22d29);
						color: #fff;
						font-size: 24rpx;
						padding: 8rpx 32rpx;
						border-radius: 24rpx;
						line-height: 1.5;
						border: none;
						box-shadow: 0 4rpx 8rpx rgba(255, 107, 107, 0.2);

						&::after {
							border: none;
						}

						&:active {
							transform: scale(0.98);
						}
					}
				}
			}
		}
	}

	.popup-content {
		background-color: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding-bottom: env(safe-area-inset-bottom);

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx;
			border-bottom: 1rpx solid #eee;
			font-size: 32rpx;

			.close {
				color: #999;
				font-size: 28rpx;
			}
		}

		.popup-list {
			max-height: 60vh;
			overflow-y: auto;

			.popup-item {
				padding: 30rpx;
				font-size: 28rpx;
				border-bottom: 1rpx solid #eee;

				&.active {
					color: #ff6b6b;
				}

				&:active {
					background-color: #f5f5f5;
				}
			}
		}
	}

	.filter-section {
		padding: 20rpx;

		.filter-item {
			display: flex;
			align-items: center;
			padding: 10rpx 20rpx;
			background: #f5f5f5;
			border-radius: 8rpx;
			font-size: 28rpx;
			color: #333;

			.sort-icon {
				margin-left: 10rpx;
				color: #666;
			}
		}
	}
</style>